package com.example.commandpattern.canvas;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PorterDuff;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.example.commandpattern.draw.DrawPath;
import com.example.commandpattern.invoker.DrawInvoker;

public class DrawCanvas extends SurfaceView implements SurfaceHolder.Callback {

    public boolean isDrawing, isRunning;

    private Bitmap mBitmap;
    private DrawInvoker invoker;
    private DrawThread drawThread;

    public DrawCanvas(Context context, AttributeSet attrs) {
        super(context, attrs);
        invoker = new DrawInvoker();
        drawThread = new DrawThread();
        getHolder().addCallback(this);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        isRunning = true;
        drawThread.start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        mBitmap = Bitmap.createBitmap(width,height,Bitmap.Config.RGB_565);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        boolean retry = true;
        isRunning = false;
        while (retry) {
            try {
                drawThread.join();
                retry = false;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    private class DrawThread extends Thread {
        @Override
        public void run() {
            Canvas canvas = null;
            while (isRunning) {
                if (isDrawing) {
                    try {
                        canvas = getHolder().lockCanvas(null);
                        if (mBitmap == null) {
                            mBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
                        }
                        Canvas a = new Canvas(mBitmap);
                        a.drawColor(0, PorterDuff.Mode.CLEAR);

                        canvas.drawColor(0,PorterDuff.Mode.CLEAR);

                        invoker.execute(a);
                        canvas.drawBitmap(mBitmap, 0, 0, null);
                    } finally {
                        getHolder().unlockCanvasAndPost(canvas);
                    }
                    isDrawing = false;
                }
            }
        }
    }

    public void add(DrawPath drawPath) {
        invoker.add(drawPath);
    }

    public void redo() {
        isDrawing = false;
        invoker.redo();
    }

    public void undo() {
        isDrawing = false;
        invoker.undo();
    }

    public boolean canUndo(){
        return invoker.canUndo();
    }

    public boolean canRedo(){
        return invoker.canRedo();
    }


}
